
package com.weiyuwqj.server.service.invest.impl;

import com.github.pagehelper.PageHelper;
import com.weiyuwqj.api.common.PageList;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.BasCoupon;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BusAccount;
import com.weiyuwqj.api.model.BusItemDeposit;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.model.BusUserStat;
import com.weiyuwqj.api.model.TicketParamEntity;
import com.weiyuwqj.api.model.vo.BasUserInviteVo;
import com.weiyuwqj.api.model.vo.BusItemInvestVo;
import com.weiyuwqj.api.model.vo.InvestDetailVo;
import com.weiyuwqj.api.model.vo.InvestSetVO;
import com.weiyuwqj.api.service.BusInvestService;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.ParamUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.BasCouponMapper;
import com.weiyuwqj.server.mapper.BasItemMapper;
import com.weiyuwqj.server.mapper.BasUserInviteMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusAccountMapper;
import com.weiyuwqj.server.mapper.BusItemDepositMapper;
import com.weiyuwqj.server.mapper.BusItemInvestMapper;
import com.weiyuwqj.server.mapper.BusUserStatMapper;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.base.BaseServiceImpl;
import com.weiyuwqj.server.service.invest.module.InvestModule;
import com.weiyuwqj.server.service.sys.module.ConfigTicketModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yandq on 15/11/22.
 */
@Service("investService")
public class BusInvestServiceImpl extends BaseServiceImpl<BasItem> implements BusInvestService{

    @Autowired
    private BusItemInvestMapper investMapper;
    @Autowired
    private BusAccountMapper accountMapper;
    @Autowired
    private BasItemMapper itemMapper;
    @Autowired
    private BasUserMapper userMapper;
    @Autowired
    private BasCouponMapper basCouponMapper;
    @Autowired
    private BusItemDepositMapper depositMapper;
    @Autowired
    private InvestModule investModule;
    @Autowired
    private BusUserStatMapper userStatMapper;
    @Autowired
    private ConfigTicketModule ticketModule;
    @Autowired
    private BasUserInviteMapper userInviteMapper;
//    @Autowired
//    private PlatformApi platformApi;

    @Override
    public PageList listInvest(Paginator p, Map<String, Object> map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusItemInvestVo> list=investMapper.getInvestList(map);
        if(list!=null){
            for(BusItemInvestVo investVo:list){
                investVo.setUsername(StringUtils.getString(investVo.getUsername()));
                investVo.setMobile(StringUtils.getString(investVo.getMobile()));
            }
        }
        return new PageList(list);
    }

    @Override
    public PageList getList(Paginator p, Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        List<BusItemInvestVo> list = investMapper.getInvestList(map); //
        PageList pageList = new PageList(list);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (BusItemInvestVo busItemInvestVo : list) {
            if (busItemInvestVo.getItemCycle() == null || busItemInvestVo.getItemCycleUnit() == null){
                continue;
            }
            Map<String, Object> beanMap = ParamUtils.getBeanMap(busItemInvestVo);
            int nowTime = DateUtils.daysOfTwo(busItemInvestVo.getAddtime(), new Date()); // 时间差
            Integer itemCycle = busItemInvestVo.getItemCycle(); // 时间
            Integer itemCycleUnit = busItemInvestVo.getItemCycleUnit(); // 周期单位
            Integer allDate = Constants.getItemCycleToDate(itemCycle, itemCycleUnit); // 总天数
            BigDecimal nowAmount = busItemInvestVo.getCollectAmount().divide(new BigDecimal(allDate),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(nowTime)); // 当前收益
            beanMap.put("nowTime", nowTime); // 当前天数
            beanMap.put("nowAmount", nowAmount.setScale(2, BigDecimal.ROUND_HALF_UP)); // 当前收益
            beanMap.put("allDate", allDate); // 总天数
            resultList.add(beanMap);
        }
        pageList.setList(resultList); // 设置转换后结果
        return pageList;
    }

    @Override
    public List<BusItemInvestVo> listInvest(Map<String, Object> map) {
        return investMapper.getInvestList(map);
    }


    /**
     *
     * @param userId 用户Id
     * @param amount 投资金额
     * @param itemId 项目Id
     * @param couponId 红包Id
     */
    @Override
    public void investCurrent(Integer userId,Double amount,Integer itemId,Integer couponId){
        if(userId<1){
            throw new CrowdException("item.invest.session_out");
        }
        BusAccount account = accountMapper.getBusAccountByUserId(userId);
        BigDecimal amountDecimal=BigDecimal.valueOf(amount);

        if(account.getUsable().compareTo(amountDecimal)<0){
            throw new CrowdException("item.invest.account_no_more_balance");
        }
        BasItem item=itemMapper.selectByPrimaryKey(itemId);
        BigDecimal itemBalance=item.getItemAccount().subtract(item.getItemOngoingAccount());

        BusItemDeposit deposit=new BusItemDeposit();


        BusItemInvest invest=new BusItemInvest();
        deposit.setUserId(userId);
        deposit.setItemId(itemId);
        deposit.setInvestAmount(amountDecimal);
        deposit.setInvestStatus(0);
        deposit.setInvestDepositAmount(BigDecimal.ZERO);
        deposit.setInvestDepositInterest(BigDecimal.ZERO);
        deposit.setInvestDepositTime(new Date());
        deposit.setInvestUndepositAmount(BigDecimal.ZERO);
        deposit.setAddtime(new Date());
        deposit.setUpdatetime(deposit.getAddtime());

        if(amountDecimal.compareTo(itemBalance)>=0){
            invest.setInvestDealAmount(itemBalance);
            itemMapper.updateItemStatus(ItemStatus.OPEN, ItemStatus.REPAYING,itemId);
        }else{
            invest.setInvestDealAmount(amountDecimal);
        }
        depositMapper.insert(deposit);
    }

    @Override
    public Double sumInvestAccount() {
        return investMapper.sumInvestAccount();
    }

    @Override
    public Double sumInvestPrincipal() {
        return investMapper.sumInvestPrincipal();
    }

    @Override
    public Double sumInvestInterest() {
        return investMapper.sumInvestInterest();
    }

    @Override
    public List<Map> getListByUserIdAndTime(Map map) {
        return investMapper.getListByUserIdAndTime(map);
    }

    //后台首页昨日今日成交统计
    @Override
    public Map countInvestAmountByTime() {
        return investMapper.countInvestAmountByTime();
    }

    //后台首页统计用户投资人数，及人次
    @Override
    public Map countInvestNum() {
        return investMapper.countInvestNum();
    }


    //后台趋势图
    @Override
    public List<Map> getRegionGroupCountInvestList(Map map) {
        return investMapper.getRegionGroupCountInvestList(map);
    }

    //根据userId和投资类型查询列表
    @Override
    public PageList getListByUserIdAndType(Paginator p,Map map) {
        PageHelper.startPage(p.getPageNum(), p.getPageSize());
        return new PageList(investMapper.getListByUserIdAndType(map));
    }


    /**
     * 根据投资记录ID投资记录详细详情
     * @param investId 投资记录ID
     * @return 投资记录详情
     */
    @Override
    public InvestDetailVo getInvestById(Integer investId) {
        return investMapper.getInvestById(investId);
    }

    @Override
    public Date getServerTime() {
        return new Date();
    }

    /**
     * 根据项目id查询投资列表
     * @param itemId 项目ID
     * @return 项目列表
     */
    @Override
    public List<BusItemInvest> getInvestListByItemId(Integer itemId) {
        return investMapper.getInvestListByItemId(itemId);
    }

    /**
     * 个人中心投资记录：标投资记录，包投资记录，债权投资记录
     * @param userId
     * @return
     */
    @Override
    public PageList getInvestSetList(Paginator p, Integer userId) {
        PageHelper.startPage(p.getPageNum(),p.getPageSize());
        List<InvestSetVO> list = investMapper.getInvestSetList(userId);
        for(InvestSetVO investSetVO:list){
            investSetVO.setDebtStatus(0);

            if(investSetVO.getStatus()==1){
                investSetVO.setDebtStatus(4);//该记录已债转
            }
            if(investSetVO.getItemStatus() <30){
                investSetVO.setDebtStatus(3);//标的未复审
            }
            if(investSetVO.getDebtTransferable()==0){
                investSetVO.setDebtStatus(2);//该标的不允许债权
            }
            if(investSetVO.getType()==3){
                investSetVO.setDebtStatus(1);//包记录不允许债转
            }
        }
        return new PageList(list);
    }


//    /**
//     * 默认PC端投资
//     * @param userId 用户ID
//     * @param amount 投资金额
//     * @param itemId 项目ID
//     * @param couponId 红包ID
//     * @param investType 投资类型
//     * @param ticketId 加息卷
//     * @return 投资结果
//     */
//    @Override
//    public Map doInvest(Integer userId,Double amount,Integer itemId,Integer couponId, Integer investType,Integer ticketId){
//        BasItem item=itemMapper.selectByPrimaryKey(itemId);
//        if(item==null){
//            throw new CrowdException("item.invest.not_exist");
//        }
//        if(item.getItemStatus()!=10){
//            throw new CrowdException("item.invest.no_invest_status");
//        }
//
//        //判断如果是新手标：新手标只支持首投
//        Map<String, Object> statMap = new HashMap<String, Object>();
//        statMap.put("userId",userId);
//        BusUserStat stat=userStatMapper.getOneByUserId(statMap);
//        if (item.getItemIsnew() == 1 && stat.getInvestCount() != 0) {
//            throw new CrowdException("item.invest.isnew_has_first");
//        }
//
//        //生成冻结订单号
//        String freeOrder = StringUtils.getOrderNo();
//
//        Map map=investModule.doInvest(userId,amount,item,couponId,investType,ticketId,freeOrder);
//
//        BigDecimal dealAmount=new BigDecimal(map.get("dealAmount").toString());
//        String investOrder=map.get("investOrder").toString();
//
//        // 调恒丰接口 ==>start
//        BasCoupon useCoupon=basCouponMapper.selectByPrimaryKey(couponId); // 红包
//        /*HfInvestAutoVo createInvestVo=new HfInvestAutoVo();
//        if(null!=useCoupon){
//            createInvestVo.setRpSubOrderId(RandomCodesUtils.createRandom(true, 8)+couponId.toString());
//            createInvestVo.setRpAmount(useCoupon.getAmount());
//            createInvestVo.setAccAmount(dealAmount.subtract(useCoupon.getAmount()));
//        }else {
//            createInvestVo.setAccAmount(dealAmount);
//            createInvestVo.setRpAmount(BigDecimal.ZERO);
//        }
//        createInvestVo.setTotalAmount(dealAmount);
//        createInvestVo.setOrderId(investOrder);
//        createInvestVo.setBidId(itemId.toString());
//        createInvestVo.setUserId(userId.toString());
//        createInvestVo.setPlatformId(userMapper.selectByPrimaryKey(userId).getPlatformId());
//        Map resultMap=investService.investAuto(createInvestVo);
//        // success_num 成功数量
//        // total_num 订单请求数量
//        if( Integer.valueOf(0).equals(resultMap.get("success_num")) ){ // 成功订单数量为0则抛出异常
//            List<Map<String, Object>> errorList = (List<Map<String, Object>>) resultMap.get("error_data");
//            throw new HfException("XfError",errorList.get(0).get("error_info").toString());
//        }*/
//        // 调恒丰接口 ==>end
//
//        //冻结投资人资金(未知红包出款方，还需冻结红包出款方红包资金金额) // 先冻结,复审再请求恒丰投资
//        HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//        if(null!=useCoupon) {
//            freezeOrTraw.setAmount(dealAmount.subtract(useCoupon.getAmount()).toString());
//        }else {
//            freezeOrTraw.setAmount(dealAmount.toString());
//        }
//        freezeOrTraw.setFreeze_flg("01");
//        freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(userId).getPlatformId());
//        freezeOrTraw.setRemark(userId+"投资冻结");
//        freezeOrTraw.setOrder_no(freeOrder);
//
//        HfResultBean<HfDataBean> result = platformApi.doFundFreeze(freezeOrTraw); // 请求恒丰
//        //if (!result.isSuccess()) { // 成功订单数量为0则抛出异常
//        //   throw new HfException("HfException", result.getMessageText());
//        //}
//        //修改冻结流水号
//	    String freezeOrderNo = "";
//        if (result.getData() != null) {
//            freezeOrderNo = result.getData().getQuery_id();
//        }
//        investMapper.modifyInvestFreezeOrderNo(freezeOrderNo,map.get("investOrder").toString());
//
//        if(stat.getInvestCount()==0) {
//            // 首次投资个人奖励
//            TicketParamEntity firstInvestParam = new TicketParamEntity();
//            firstInvestParam.setNid(Constants.first_invest_nid);
//            firstInvestParam.setUserId(userId);
//            ticketModule.addTicket(firstInvestParam);
//
//            //首次投资邀请人奖励
//            BasUserInviteVo userInvite = userInviteMapper.getOneByInviteId(userId);
//            if(userInvite !=null){
//                TicketParamEntity firstInvesInvitetParam = new TicketParamEntity();
//                firstInvesInvitetParam.setNid(Constants.first_invite_invest_nid);
//                firstInvesInvitetParam.setUserId(userInvite.getUserId());
//                firstInvesInvitetParam.setAmount(dealAmount);
//                ticketModule.addTicket(firstInvesInvitetParam);
//            }
//        }
//
//        //单笔投资满额奖励
//        TicketParamEntity investParam = new TicketParamEntity();
//        investParam.setNid(Constants.invest_nid);
//        investParam.setUserId(userId);
//        investParam.setAmount(dealAmount);
//        ticketModule.addTicket(investParam);
//
//        //总投资满额奖励
//        TicketParamEntity totalInvestParam = new TicketParamEntity();
//        totalInvestParam.setNid(Constants.total_invest_nid);
//        totalInvestParam.setUserId(userId);
//        ticketModule.addTicket(totalInvestParam);
//
//        //修改先锋订单表
//        return Message.OK;
//    }

    @Override
    public Map<String,Object> getOne(Integer itemId) {
        return investMapper.getOne(itemId);
    }

}
